<script lang="ts" setup>
// 父组件传递数据
const props = defineProps({
  limitCountFile: {
    type: Number,
    default: 1,
  },
  backFile: {
    type: Array,
    default: [],
  },
  editIndex: {
    type: Number,
    default: null,
  },
});
// 定义暴露事件名
const emit = defineEmits(['handleFileSuccess']);

/**
 * 上传文件配置：
 * uploadRef 上传组件ref
 * fileConfig: {
    fileList: [], // 上传文件列表
  }
 * handelExceed 上传的文件个数超出设定时触发的函数
 * handelRemove
 */
const uploadRef = ref(null);
const fileConfig = reactive({
  serverUrls: 'http://hxbfb.bailingkeji.com/login/upload',
  fileList: [],
});

if (props.backFile['file']) {
  fileConfig.fileList.push({
    name: props.backFile['content'],
    url: props.backFile['file'][0],
  });
}

const handelExceed = () => {
  ElMessage.warning({ message: `最多只能上传${props.limitCountFile}个文件` });
};
const handelRemove = (file, fileList) => {
  emit('handleFileSuccess', fileList, props.editIndex);
};
const handleSuccess = (response, file, fileList) => {
  if (response.code != 200)
    return ElMessage.error({
      message: `文件上传失败!`,
    });
  emit('handleFileSuccess', response, props.editIndex);
};
</script>

<template>
  <div class="upload_file">
    <el-upload :action="fileConfig.serverUrls" class="upload-demo" :limit="props.limitCountFile"
      :on-exceed="handelExceed" :on-remove="handelRemove" :on-success="handleSuccess" :file-list="fileConfig.fileList"
      ref="uploadRef">
      <el-button type="primary">
        <el-icon style="margin-right: 3px">
          <Plus />
        </el-icon>
        上传文件
      </el-button>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.upload_file {
  width: 80%;

  ::v-deep .el-upload-list {
    margin: 10px 0 0 0;
  }
}
</style>
